'use strict';

const Service = require('egg').Service;

class BooksService extends Service {
  /**
     * 根据ID获取单个项目
     */
   async getProjectById(title) {
    const { ctx, app } = this;
    try {
      // Books为modal/books.js里面命名的名字
      const results = await ctx.model.Books.find({ title });
      // {
      //   _id: app.mongoose.Types.ObjectId('5da034149b6e823ca2ea809d'),
      // }
      return results;
    } catch (err) {
      ctx.body = JSON.stringify(err);
    }
  }

  async queryByTitle(title) {
    const { ctx } = this;
    try {
      // Books为modal/books.js里面命名的名字
      const results = await ctx.model.Books.find({ title });
      return results;
    } catch (err) {
      ctx.body = JSON.stringify(err);
    }
  }

  async addBook() {
    const { ctx, app } = this;
    // {username: 'jack', userpassword: '123456'}
    try {
      const query = this.ctx.request.query;
      console.log(query, typeof query);
      if (!query.title) return JSON.stringify({ error: '请传入标题' });
      if ((await this.queryByTitle(query.title)).length) return JSON.stringify({ error: '已经存在了: '+query.title });
      // const result = await this.ctx.model.Books.insertMany(query);  // 插入多条文档
      const result = await this.ctx.model.Books.create(query);  // 插入一条
      // const result = await this.ctx.model.Books.updateOne(query) // 删除一条文档
      return result;
    } catch (err) {
      ctx.body = JSON.stringify(err);
    }
  }
}
module.exports = BooksService;
